import { Modal, Upload, Progress, Button, message, Spin } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { FC } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { TOKEN } from '@/common/const';
import storage from '@/utils/storage';
import styles from './index.less';
import imgSrc from './plus.svg';
import duiSrc from './dui.svg';
import closeSrc from './x.svg';
import classnames from 'classnames';

// const { Dragger } = Upload;

const delay = (time: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
const Index: FC<{
  visible?: boolean;
  onCancel?: () => void;
  onOk: (val: any[]) => void;
  action: string;
  payload: any;
  name?: string;
  getContainer?: () => any;
}> = ({ visible, onCancel, onOk, action, payload, name = 'file', getContainer }) => {
  const [fileList, setFileList] = useState<any[]>([]);
  const [selected, setSelected] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const delaySetFileList = async (fileList) => {
    await delay(100);
    setFileList([...fileList]);
  };
  const handleChange = ({ fileList: newFileList }) => {
    setFileList([...newFileList]);
    // !延迟重新更新下数据，如不操作，图片无法正常显示
    if (!newFileList.some((item) => item.status !== 'done')) {
      delaySetFileList([...newFileList]);
    }
  };

  const selectAll = useCallback(() => {
    setSelected([...fileList]);
  }, [fileList]);
  const ok = async () => {
    if (!selected.length) {
      message.error('请先选择插入的图片');
      return;
    }
    setLoading(true);
    await delay(2500);
    onOk([...selected]);
  };
  const remove = (uid) => {
    setFileList([...fileList].filter((item) => item.uid !== uid));
    setSelected([...selected].filter((item) => item.uid !== uid));
  };
  useEffect(() => {
    console.log(fileList);
  }, [fileList]);
  useEffect(() => {
    if (visible === false) {
      setSelected([]);
    }
    setLoading(false);
  }, [visible]);
  return (
    <Modal
      open={visible}
      wrapClassName={classnames('c-lecturer-chapter-modal-wrap-container', styles.container)}
      maskClosable={false}
      closable={false}
      onCancel={onCancel}
      footer={null}
      width={810}
      getContainer={getContainer}
      onOk={ok}
      zIndex={2080}
      okText={'插入所选项'}
    >
      <Spin spinning={loading} tip="正在保存中...">
        <div style={{ lineHeight: '62px', textAlign: 'center', color: '#E5F5EF', fontSize: 16 }}>
          上传图片
        </div>
        <div className={styles.upload} style={{ padding: '0 20px' }}>
          <Upload
            action={action}
            accept=".jpg,.jpeg,.png,.gif,.webp"
            listType="picture-card"
            fileList={fileList}
            // showUploadList={false}
            multiple
            onChange={handleChange}
            data={payload}
            name={name}
            headers={{
              token: (storage.get(TOKEN) || {}).value,
            }}
          >
            <img width={36} height={36} src={imgSrc} alt="" />
          </Upload>
          {fileList?.map((item, index) => {
            return (
              <Spin
                spinning={item.status !== 'done'}
                key={
                  index === fileList.length - 1
                    ? JSON.stringify(item) + Date.now()
                    : JSON.stringify(item)
                }
                tip="上传中..."
              >
                <span
                  className={classnames(styles.img, {
                    [styles.selected]: selected.some((it) => it.uid === item.uid),
                  })}
                  onClick={() => {
                    if (selected.some((it) => it.uid === item.uid)) {
                      setSelected([...selected].filter((it) => it.uid !== item.uid));
                    } else {
                      setSelected([...selected, item]);
                    }
                  }}
                >
                  {/*<img key={item.status} src={item.response?.data?.url || item.thumbUrl} alt="" />*/}
                  <img key={item.status + item.thumbUrl} src={item.thumbUrl} alt="" />
                  <i onClick={() => remove(item.uid)} className={styles.close} />
                </span>
              </Spin>
            );
          })}
        </div>
        <div className={styles.footer}>
          <span>
            <span onClick={selectAll}>
              <img src={duiSrc} alt="" />
              选择全部
            </span>
            <span onClick={() => setSelected([])}>
              <img src={closeSrc} alt="" />
              取消全部
            </span>
          </span>
          <span>
            <Button onClick={onCancel}>取消</Button>
            <Button loading={loading} onClick={ok} type="primary">
              插入所选项
            </Button>
          </span>
        </div>
      </Spin>
    </Modal>
  );
};

export default Index;
